<!--
 * @Description: 控制分组管理页面
-->
<template>
  <BaseMainSlot :show-tab="true">
    <template v-slot:btn-box>
      <ActionBar :page-no="102" :add-active="addActive" :del-active="delActive" :edit-active="editActive" :has-edit="false" :has-save="false" :cancel-active="cancelActive" :save-active="saveActive" @add="add" @cancel="cancel('formData')" @edit="edit" @del="del" @save="save('formData')" />
    </template>
    <template v-slot:search-box>
      <SearchForm :formConfig="formConfig" :formData="searchlist" @search="search"></SearchForm>
    </template>
    <template v-slot:table-box>
      <div class="control-content">
        <div class="left">
          <div class="sid-head">选择设施</div>
          <div class="sid-tree">
            <treeSide :queryType="2" @treeselectvalue="treeselectvalue" />
          </div>
        </div>
        <div class="right">
          <Table :propList="tableColumn" v-loading="loading" :listData="tableData" @handleSelectionChange="handleSelectionChange">
            <template v-slot:facility="{ row }">
              <template v-if="row.groupNo">
                <el-button class="text-btn-cursor" type="text" size="small" @click="seeEquip(row)"> <i class="el-icon-view"></i> 查看 </el-button>
              </template>
            </template>
            <template v-slot:operation="{ row }">
              <template v-if="!row.index && row.groupNo">
                <!-- v-if="judgePermission(102, 'edit')" -->
                <el-button class="text-btn-cursor" type="text" size="small" style="height: 15px" @click="handleEdit(row, 'edit')"><i class="el-icon-edit-outline"></i>修 改</el-button>
                <!-- v-if="judgePermission(102, 'delete')" -->
                <el-button class="text-btn-cursor cursor-delete" type="text" size="small" @click="handleDelete(row)"><i class="el-icon-delete"></i> 删除</el-button>
              </template>
            </template>
          </Table>
        </div>
      </div>
      <Pagination :page-size="pageSize" :current-page="currentPage" :total-size="totalSize" @changePageSize="changePageSize" @changeCurrentPage="changeCurrentPage" />
    </template>
    <template v-slot:dialog>
      <el-dialog :title="titleText + '控制分组'" :visible.sync="dialogFormVisible">
        <el-form ref="formData" label-position="left" :model="formData" :rules="rules" class="el-form">
          <el-form-item label="分组名称:" prop="groupName" class="w100p">
            <el-input v-model="formData.groupName" placeholder="" clearable />
          </el-form-item>
          <el-form-item label="关联数据项类型:" prop="dataTypeId" class="w100p">
            <el-select
              v-model="formData.dataTypeId"
              placeholder="请选择关联数据项类型"
              filterable
              clearable
              @change="dataTypeChange()"
            >
              <el-option
                v-for="item in dataTypeList"
                :key="item.dataTypeId"
                :label="item.dataTypeName"
                :value="item.dataTypeId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="关联数据项:" prop="dataItemIds" class="w100p">
            <el-select v-model="formData.dataItemIds" placeholder="请选择关联数据项" filterable clearable multiple collapse-tags>
              <el-option v-for="item in dataItemList" :key="item.dataItemId" :label="item.dataItemName" :value="item.dataItemId" />
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel">
            取 消
          </el-button>
          <el-button class="zh-button-two" type="primary" @click="save('formData')">
            保 存
          </el-button>
        </div>
      </el-dialog>
      <el-dialog title="数据项列表" :visible.sync="isShowEquip" width="30%" class="dialogRec" :before-close="cancelData">
        <div class="facility-list">
          <div v-for="(item, index) in facilityBOList" :key="index" class="facility-item">
            <div class="info-line">
              <div class="name">数据项类型：</div>
              <div class="value">{{ item.dataTypeName }}</div>
            </div>
            <div class="info-line">
              <div class="name">数据项名称：</div>
              <div class="value">{{ item.dataItemName }}</div>
            </div>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancelData">关 闭</el-button>
        </span>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import ActionBar from '@/components/ActionBar';
import Pagination from '@/components/Pagination';
import controlApi from '@/api/basic-info-manage/control-group-management';
import SearchForm from '@/components/searchForm';
import BaseMainSlot from '@/components/BaseMainSlot/newBaseMainSlot.vue';
import treeSide from '@/components/selectbutton/trelist.vue';
import Table from '@/components/table/table.vue';
import SeeEquip from '@/components/seeEquip/index.vue';
import { mymixin } from '@/utils/mixins';
import { mapGetters } from 'vuex';
import Axios from 'axios';
export default {
  // eslint-disable-next-line vue/name-property-casing
  name: 'dataManagement',
  components: { Pagination, BaseMainSlot, SearchForm, ActionBar, treeSide, Table, SeeEquip },
  mixins: [mymixin],
  data() {
    return {
      formConfig: [
        {
          label: '分组名称',
          prop: 'groupName',
          type: 'input'
        }
      ],
      searchlist: {},
      dataTypeList: [],
      dataItemList: [],
      rules: {
        groupName: [{ required: true, message: '分组名称不能为空', trigger: 'blur' }],
        dataTypeId: [{ required: true, message: '关联数据项类型不能为空', trigger: 'blur' }],
        dataItemIds: [{ required: true, message: '关联数据项不能为空', trigger: 'blur' }]
      },
      tableColumn: [
        { prop: 'groupName', label: '分组名称', minWidth: '200' },
        { prop: 'groupNos', label: '分组包含数据项', slotName: 'facility', minWidth: '150' },
        { prop: 'operation', label: '操作', slotName: 'operation', width: '200' }
      ],
      tableData: [],
      loading: false,
      // 选中的id数组 ID组成
      idList: [],
      dialogFormVisible: false,
      deviceName: '',
      isShowEquip: false,
      facilityBOList: []
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: 'permission/judgePermission'
    })
  },
  watch: {},
  created() {
    this.queryAllDataType();
    // 获取表格数据
    // this.getTableDataList();
  },
  mounted() {},
  methods: {
    queryAllDataType() {
      controlApi.queryAllDataType().then(res => {
        this.dataTypeList = res.data;
      });
    },
    dataTypeChange (dataItemIds) {
      controlApi.queryByConditionDataItem({
        control: true,
        facilityNo: this.facilityNo,
        dataTypeId: this.formData.dataTypeId,
      }).then(res => {
        this.dataItemList = res.data
        this.$set(this.formData, 'dataItemIds', dataItemIds || [])
      })
    },
    // 点击树状触发方法
    treeselectvalue(e) {
      this.paramslist = {};
      this.facilityNo = e.facilityNo;
      console.log(e);
      this.facilityName = e.facilityName;
      this.addActive = true;
      if (e.facilityGroupNo) {
        this.paramslist['facilityGroupNo'] = e.facilityGroupNo;
      } else if (e.facilityNo) {
        this.paramslist['facilityNo'] = e.facilityNo;
      }
      // 当前选中的组织结构id
      this.nowselctorgid = e.organizationNo;
      this.getTableDataList();
    },
    // 获取表格数据
    getTableDataList() {
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          ...this.searchlist,
          facilityNo: this.facilityNo,
          farmingTypeNo: sessionStorage.farmingTypeNo,
          organizationNo: sessionStorage.organizationNo
        }
      };
      this.loading = true;
      controlApi
        .queryPageByCondition(params)
        .then(res => {
          this.loading = false;
          let data = res.data;
          if (data) {
            this.totalSize = data.totalElements;
            this.tableData = data.content;
            this.addblankmet();
            this.resetActionBar();
          }
        })
        .catch(() => {
          this.loading = false;
        });
    },
    dateFormat(row, colnum) {
      return this.$moment(row[colnum.property]).format('YYYY-MM-DD');
    },
    search() {
      this.currentPage = 1;
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    async handleEdit(row) {
      // TODO 点击行元素后 edit
      this.formData = { ...row };
      const { data } = await controlApi.queryDataItemMapper(
        row.groupNo
      );
      let dataItemIds = data.map(el => { return el.dataItemId })
      // this.$set(this.formData, 'dataItemIds', dataItemIds)
      this.dataTypeChange(dataItemIds)
      this.dialogFormVisible = true
      this.nowChanceStau = "edit"
    },
    handleSelectionChange(list) {
      this.idList = [];
      this.idList = list.map(item => item.groupNo);
      if (this.idList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    delmessage() {
      controlApi
        .delList({
          groupNos: this.idList
        })
        .then(res => {
          if (res.code === 1) {
            this.$message.success(res.msg);
            this.getTableDataList();
          } else {
            this.$message.warning(res.msg || '删除失败');
          }
        });
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        customClass: 'myClass'
      })
        .then(() => {
          controlApi.delByNo(row.groupNo).then(res => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.getTableDataList();
            } else {
              this.$message.warning(res.msg || '删除失败');
            }
          });
        })
        .catch(() => {
          //
          this.$message('取消删除');
        });
    },
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.nowChanceStau === 'edit') {
            // 编辑接口
            // 巡检点数组赋值进formData
            controlApi.edit(this.formData).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || '修改成功！');
                // this.postId = "";
                this.getTableDataList();
                this.$refs[formData].resetFields();
              } else {
                this.$message.error(res.msg || '修改失败！');
              }
            });
          } else if (this.nowChanceStau === 'add') {
            controlApi
              .add({
                ...this.formData,
                facilityNo: this.facilityNo
              })
              .then(res => {
                if (res.code === 1) {
                  this.$message.success(res.msg || '新增成功！');
                  // this.postId = "";
                  this.getTableDataList();
                  this.$refs[formData].resetFields();
                } else {
                  this.$message.error(res.msg || '新增失败！');
                }
              });
          }
        } else {
          return false;
        }
      });
    },
    // 查看数据项
    async seeEquip(row) {
      const { data: res } = await controlApi.queryDataItemMapper(row.groupNo);
      if (res && res.length) {
        this.isShowEquip = true;
        this.facilityBOList = res;
      } else {
        this.$message.warning('暂无设施');
      }
    },
    cancelData() {
      this.isShowEquip = false;
    }
  }
};
</script>

<style scoped lang="scss">
@import '~@/styles/variables.scss';
.control-content {
  width: 100%;
  height: calc(100% - 45px);
  display: flex;
  .left {
    width: 300px;
    height: 100%;
    margin-right: 10px;
    padding: 10px;
    background-color: #074052;

    .sid-head {
      width: 100%;
      height: 40px;
      line-height: 40px;
      font-size: 18px;
      font-weight: 600;
      text-align: center;
      border-bottom: #fff dashed 1px;
    }

    .sid-tree {
      width: 100%;
      height: calc(100% - 31px);
      padding: 10px 0 0 10px;
    }
    ::v-deep {
      .el-tree-node:first-child {
        margin-top: 0;
      }
    }
  }
  .right {
    width: calc(100% - 300px);
    ::v-deep {
      .el-table {
        height: 100% !important;
      }
    }
  }
}

::v-deep {
  .el-form-item__label {
    min-width: 140px !important;
  }
}
.dialogRec.el-dialog__wrapper {
  ::v-deep .el-dialog {
    height: auto;
    // width: 33% !important;
    .el-dialog__body {
      height: auto;
      overflow-y: auto;
      text-align: center;
      font-size: 18px;
      // color: red;
      letter-spacing: 2px;
      font-weight: 600;
      span {
        line-height: 100px;
      }
    }
    .el-dialog__footer {
      .Reconfirmation {
        background-color: #096f8f;
        border-radius: 6px;
      }
      .correct {
        background-color: #fff;
        color: #096f8f;
        border-radius: 6px;
        border: 1px solid #096f8f;
      }
    }
  }
}
.facility-list {
  display: flex;
  justify-content: flex-start;
  flex-direction: row;
  flex-wrap: wrap;
  .facility-item {
    width: 45%;
    margin-right: 3%;
    margin-bottom: 10px;
    // height: 80px;
    border-radius: 5px;
    // border: 1px solid #ccc;
    box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.15);
    padding: 10px 20px;

    .info-line {
      display: flex;
      justify-content: flex-start;
      align-items: flex-start;
      font-size: 14px;
      &:not(:last-child) {
        margin-bottom: 10px;
      }
      .name {
        text-align: left;
        width: 100px;
        flex-shrink: 0;
      }
      .value {
        width: 100%;
        text-align: left;
        font-weight: normal;
      }
    }
  }
}
</style>
